<?php

namespace app\controllers;
use Yii;
use app\tools\Re;
use app\models\Customer;
use app\models\CustomerHistory;

class CustomerHistoryController extends BaseController
{
    //我的足迹
    public function actionHistoryList(){
      $openid = Yii::$app->request->post('openid', '');
      $page = Yii::$app->request->post('page', 0);
      $page_size = Yii::$app->request->post('page_size', 10);
      $customer_info = Customer::find()->where(['openid' => $openid])->one();
      if (!$customer_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      $list = CustomerHistory::find()->where(['customer_id' => $customer_info->id])
        ->orderBy('created_at desc')
        ->limit($page_size)
        ->offset($page_size*$page)
        ->all();;
      $data = [];
      if ($list) {
        foreach ($list as $v) {
          $data[] = [
            'id' => $v->id,
            'good_id' => $v->good->id,
            'good_name' => $v->good->name,
            'good_img' => $v->good->cover,
            'good_price' => $v->good->price,
            'good_unit_name' => $v->good->unit_name,
            'created_time' => date('Y-m-d H:i:s', $v->created_at)
          ];
        }
      }
      return Re::data(['data' => $data]);
    }

    //删除我的足迹
    public function actionDeleteHistory(){
      $id = Yii::$app->request->post('id', '');
      $openid = Yii::$app->request->post('openid', '');
      $customer_info = Customer::find()->where(['openid' => $openid])->one();
      if (!$customer_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      $history_info = CustomerHistory::findOne($id);
      if (!$history_info) {
        return Re::data(null, '信息读取错误', Re::ERROR);
      }
      $history_info->delete();
      return Re::data();
    }

    //清空我的足迹
    public function actionClearHistory(){
      $openid = Yii::$app->request->post('openid', '');
      $customer_info = Customer::find()->where(['openid' => $openid])->one();
      if (!$customer_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      CustomerHistory::deleteAll(['customer_id' => $customer_info->id]);
      return Re::data();
    }
}
